App({
  globalData: {
    userInfo: null,
    loginCode: '',
    token: '',
    // API基础地址配置
    apiBaseUrl: {
      development: 'http://localhost:3000/api',
      production: 'https://your-api-domain.com/api' // 生产环境API地址
    },
    // 当前环境
    environment: 'development' // 可根据需要切换为'production'
  },
  
  onLaunch: function () {
    console.log('小程序启动');
    
    // 初始化时检查是否有登录状态和用户信息
    this.initUserInfo();
  },
  
  // 初始化用户信息
  initUserInfo: function() {
    try {
      // 获取token
      const token = wx.getStorageSync('token');
      if (token) {
        this.globalData.token = token;
      }
      
      // 获取用户信息
      const userInfo = wx.getStorageSync('userInfo');
      if (userInfo) {
        this.globalData.userInfo = JSON.parse(userInfo);
      }
      
      // 获取登录code
      const loginInfo = wx.getStorageSync('loginInfo');
      if (loginInfo) {
        this.globalData.loginCode = loginInfo.code;
      }
    } catch (e) {
      console.error('获取登录状态失败:', e);
    }
  },
  
  // 保存用户信息到全局和本地存储
  saveUserInfo: function(userInfo, token) {
    this.globalData.userInfo = userInfo;
    this.globalData.token = token;
    
    try {
      wx.setStorageSync('userInfo', JSON.stringify(userInfo));
      wx.setStorageSync('token', token);
    } catch (e) {
      console.error('保存用户信息失败:', e);
    }
  },
  
  // 清除用户信息
  clearUserInfo: function() {
    this.globalData.userInfo = null;
    this.globalData.token = '';
    this.globalData.loginCode = '';
    
    try {
      wx.removeStorageSync('userInfo');
      wx.removeStorageSync('token');
      wx.removeStorageSync('loginInfo');
    } catch (e) {
      console.error('清除用户信息失败:', e);
    }
  },
  
  // 获取当前环境的API基础地址
  getApiBaseUrl: function() {
    return this.globalData.apiBaseUrl[this.globalData.environment] || this.globalData.apiBaseUrl.development;
  }
})
